from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from goods.models import SPU, Brand, GoodsCategory
from meiduo_admin.serializers.spus import SPUSSeriazlier, SPUBrandsSerizliser, CategorysSerizliser
from meiduo_admin.utils import PageNum


class SpuView(ModelViewSet):
    """ SPU表的增删改查"""
    # 指定序列化器
    serializer_class = SPUSSeriazlier
    # 指定查询集
    queryset = SPU.objects.all()
    # 指定分页器
    pagination_class = PageNum
    # 指定权限
    permission_classes = [IsAdminUser]

    # 获取品牌
    def brand(self, request):
        data = Brand.objects.all()
        ser = SPUBrandsSerizliser(data, many=True)
        return Response(ser.data)
    # 获取1级分类
    def channel(self, request):
        data = GoodsCategory.objects.filter(parent=None)
        ser = CategorysSerizliser(data, many=True)
        return Response(ser.data)
    # 获取2级分类
    def channels(self, request, pk):
        data = GoodsCategory.objects.filter(parent_id=pk)
        ser = CategorysSerizliser(data, many=True)
        return Response(ser.data)

    @action(methods=['post'], detail=False)
    def image(self, request):
        # 1、获取图片数据
        data = request.FILES.get('image')
        # 验证图片数据
        if data is None:
            return Response(status=500)

        # 2、建立fastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)

        # 3、上传图片
        res = client.upload_by_buffer(data.read())

        # 4、判断上传状态
        if res['Status'] != 'Upload successed.':
            return Response({'error': '上传失败'}, status=501)

        # 5、获取上传的图片路径
        image_url = res['Remote file_id']

        # 6、结果返回
        return Response(
            {
                'img_url': settings.FDFS_URL + image_url
            },

            status=201
        )

class SPUGoodsView(ModelViewSet):
    """
        SPU表
    """
    serializer_class = SPUSSeriazlier
    queryset = SPU.objects.all()
    pagination_class = PageNum